package mx.com.fractal.ristorante.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import mx.com.fractal.ristorante.dao.ClienteDAO;
import mx.com.fractal.ristorante.dto.ClienteDTO;
import mx.com.fractal.ristorante.dto.TipoPersona;
import mx.com.fractal.ristorante.util.ParamSrcUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

@Repository
public class ClienteDAOImpl implements ClienteDAO {

	private static final String INSERT = "INSERT INTO "
			+ ParamSrcUtil.getTableName(ClienteDTO.class)
			+ " (id_restaurante,id_direccion,tipo_persona,razon_social,rfc,"
			+ "nombre,ap_paterno,ap_materno,telefono,celular) VALUES("
			+ ":idRestaurante, :idDireccion, :tipoPersona,:razonSocial,:rfc,"
			+ ":nombre,:apPaterno,:apMaterno,:telefono,:celular)";
	@Autowired
	private NamedParameterJdbcTemplate jdbc;
	
	
	public Integer save(ClienteDTO cliente) {
		MapSqlParameterSource parameters = ParamSrcUtil.getParams(cliente);
		
		parameters.addValue("tipoPersona", cliente.getTipoPersona().toString());
		if(cliente.getDireccion()!= null){
			parameters.addValue("idDireccion", cliente.getDireccion().getIdDireccion());
		}else{
			parameters.addValue("idDireccion", null);
		}
		GeneratedKeyHolder holder = new GeneratedKeyHolder();
		jdbc.update(INSERT, parameters, holder);
		
		return (Integer) holder.getKeys().get("id_cliente");
	}

	private static final String GET_ALL="SELECT id_cliente,tipo_persona,id_restaurante"
			+ "razon_social,rfc,nombre,ap_paterno,ap_materno,telefono,celular,fecha_nacimiento,email "
			+ " FROM "+ ParamSrcUtil.getTableName(ClienteDTO.class);
	
	public List<ClienteDTO> getAllBy(ClienteDTO conditions) throws SQLException {
		String where = ParamSrcUtil.getWhereFromObject(conditions);
		SqlParameterSource paramMap = ParamSrcUtil.getParams(conditions);
		List<ClienteDTO> clientes = jdbc.query(GET_ALL+where, paramMap, new ClientRowMapper());
		return clientes;
	}
	
	private class ClientRowMapper implements RowMapper<ClienteDTO>{

		public ClienteDTO mapRow(ResultSet rs, int index) throws SQLException {
			ClienteDTO cliente=new ClienteDTO();
			cliente.setTipoPersona(TipoPersona.valueOf(rs.getString("tipo_persona")));
			ParamSrcUtil.setValuesFromResultSet(cliente, rs);
			return cliente;
		}
	}
}